<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="题目类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择题目类型" clearable style="width:220px">
          <el-option
              v-for="dict in question_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属圈子" prop="circleId">
        <el-select v-model="queryParams.circleId" placeholder="请选择所属圈子" clearable style="width:220px">
          <el-option
              v-for="item in circleOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属文章" prop="generatedTextId">
        <el-select v-model="queryParams.generatedTextId" placeholder="请选择所属文章" clearable style="width:220px">
          <el-option
              v-for="item in digestOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-for="btn in actionButtons" :key="btn.type">
        <el-button
            :type="btn.type"
            plain
            :icon="btn.icon"
            :disabled="btn.disabled"
            @click="btn.handler"
            v-hasPermi="btn.permission"
        >{{ btn.text }}</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 卡片式布局替代表格 -->
    <div v-loading="loading" class="question-cards-container">
      <div v-if="questionList.length === 0 && !loading" class="empty-state">
        <el-empty description="暂无题目数据" />
      </div>

      <div v-else class="question-cards">
        <div
            v-for="(item, index) in questionList"
            :key="item.id"
            class="question-card"
            :class="{ 'selected': selectedIds.includes(item.id) }"
        >
          <div class="card-header">
            <el-checkbox
                :model-value="selectedIds.includes(item.id)"
                @change="(checked) => handleCardSelection(item.id, checked)"
            />
            <div class="card-title">
              <span class="question-number">#{{ (queryParams.pageNum - 1) * queryParams.pageSize + index + 1 }}</span>
              <span class="question-type">
                <dict-tag :options="question_type" :value="item.questionType"/>
              </span>
              <span class="circle-indicator">{{ getCircleNameById(item.circleId) }}</span>
            </div>
            <div class="card-status">
              <dict-tag :options="processedQuestionStatus" :value="item.questionStatus"/>
            </div>
          </div>

          <div class="card-content">
            <div class="question-title-section">
              <h3 class="question-title" :class="{ 'expanded': expandedCards.includes(item.id) }">
                {{ item.questionTitle }}
              </h3>
              <el-button
                  v-if="item.questionTitle && item.questionTitle.length > 100"
                  type="text"
                  size="small"
                  @click="toggleExpand(item.id)"
                  class="expand-btn"
              >
                {{ expandedCards.includes(item.id) ? '收起' : '展开' }}
              </el-button>
            </div>

            <div class="question-options" v-if="item.questionOptions">
              <div class="options-title">选项：</div>
              <div class="options-list">
                <div
                    v-for="option in parseOptions(item.questionOptions)"
                    :key="option.optionId"
                    class="option-item"
                    :class="{ 'correct': isCorrectAnswer(option.optionId, item.correctAnswer, item.questionType) }"
                >
                  <span class="option-id">{{ option.optionId }}.</span>
                  <span class="option-content">{{ option.optionContent }}</span>
                </div>
              </div>
            </div>

            <div class="question-meta">
              <div class="meta-item" v-for="meta in getMetaItems(item)" :key="meta.label">
                <span class="meta-label">{{ meta.label }}：</span>
                <span class="meta-value" :class="meta.class">{{ meta.value }}</span>
              </div>
            </div>

            <div class="question-info">
              <div class="info-item" v-for="info in getInfoItems(item)" :key="info.label">
                <span class="info-label">{{ info.label }}：</span>
                <span class="info-value" :class="info.class">{{ info.value }}</span>
              </div>
            </div>
          </div>

          <div class="card-actions">
            <el-button
                v-for="action in getCardActions(item)"
                :key="action.type"
                link
                :type="action.type"
                :icon="action.icon"
                @click="action.handler"
                v-hasPermi="action.permission"
            >{{ action.text }}</el-button>
          </div>
        </div>
      </div>
    </div>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改题目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="100px">
        <div class="form-row">
          <el-form-item
              v-for="field in getFormFields()"
              :key="field.prop"
              :label="field.label"
              :prop="field.prop"
              :class="field.class"
          >
            <el-select
                v-model="form[field.prop]"
                :placeholder="field.placeholder"
                style="width: 100%;"
            >
              <el-option
                  v-for="item in field.options"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="问题标题" prop="questionTitle">
          <el-input v-model="form.questionTitle" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
        <div class="form-row">
          <el-form-item label="题目类型" prop="questionType" class="form-item-half">
            <el-select v-model="form.questionType" placeholder="请选择题目类型" style="width: 100%;">
              <el-option
                  v-for="dict in question_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题目状态" prop="questionStatus" class="form-item-half">
            <el-select v-model="form.questionStatus" placeholder="请选择题目状态" style="width: 100%;">
              <el-option
                  v-for="dict in question_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="选项" prop="questionOptions" v-if="form.questionType === 1 || form.questionType === 2">
          <div class="options-container">
            <div v-for="(option, index) in form.questionOptions" :key="index" class="option-item">
              <el-input v-model="option.optionContent" placeholder="请输入选项内容" style="flex: 1;">
                <template #prepend>{{ option.optionId }}</template>
              </el-input>
              <el-button type="danger" icon="Delete" @click="removeOption(index)" v-if="form.questionOptions.length > 2" style="margin-left: 8px;">删除</el-button>
            </div>
            <el-button type="primary" icon="Plus" @click="addOption" v-if="form.questionOptions.length < 6" style="margin-top: 8px;">添加选项</el-button>
          </div>
        </el-form-item>
        <el-form-item label="正确答案" prop="correctAnswer">
          <!-- 单选题 -->
          <el-radio-group v-model="form.correctAnswer" v-if="form.questionType === 1">
            <el-radio v-for="option in form.questionOptions" :key="option.optionId" :label="option.optionId">
              {{ option.optionId }}
            </el-radio>
          </el-radio-group>

          <!-- 多选题 -->
          <el-checkbox-group v-model="form.correctAnswer" v-if="form.questionType === 2">
            <el-checkbox v-for="option in form.questionOptions" :key="option.optionId" :label="option.optionId">
              {{ option.optionId }}
            </el-checkbox>
          </el-checkbox-group>

          <!-- 判断题 -->
          <el-radio-group v-model="form.correctAnswer" v-if="form.questionType === 3">
            <el-radio label="A">正确</el-radio>
            <el-radio label="B">错误</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案解释" prop="answerExplanation">
          <el-input v-model="form.answerExplanation" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>
        <div class="form-row">
          <el-form-item label="答对奖励积分" prop="rewardPoints" class="form-item-half">
            <el-input v-model="form.rewardPoints" placeholder="请输入答对奖励积分" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- AI生成题目对话框 -->
    <el-dialog title="AI生成题目" v-model="generateOpen" width="1000px" append-to-body>
      <el-form ref="generateRef" :model="generateForm" :rules="generateRules" label-width="130px" class="ai-generate-form">
        <div class="ai-generate-form-row">
          <el-form-item label="所属圈子" prop="circleId" class="form-item-half circle-form-item">
            <el-select v-model="generateForm.circleId" placeholder="请选择所属圈子" style="width: 100%;">
              <el-option
                  v-for="item in circleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所属文章" prop="generatedTextId" class="form-item-half">
            <el-select v-model="generateForm.generatedTextId" placeholder="请选择所属文章" style="width: 100%;">
              <el-option
                  v-for="item in digestOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="ai-generate-form-row">
          <el-form-item label="文章标题" prop="generatedTitle" class="form-item-half">
            <el-input v-model="generateForm.generatedTitle" placeholder="请输入文章标题" />
          </el-form-item>
          <el-form-item label="答对奖励积分" prop="rewardPoints" class="form-item-quarter">
            <el-input v-model="generateForm.rewardPoints" placeholder="请输入答对奖励积分" />
          </el-form-item>
          <el-form-item label="题目状态" prop="questionStatus" class="form-item-quarter">
            <el-select v-model="generateForm.questionStatus" placeholder="请选择题目状态" style="width: 100%;">
              <el-option
                  v-for="dict in question_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="ai-generate-form-row">
          <el-form-item label="文章内容" prop="generatedArticle" class="form-item-full">
            <el-input v-model="generateForm.generatedArticle" type="textarea" :rows="10" placeholder="请输入文章内容" class="ai-article-textarea" />
          </el-form-item>
        </div>
        <el-upload
          :show-file-list="false"
          accept=".docx"
          :before-upload="handleWordUpload"
          class="word-upload-btn"
        >
          <el-button type="primary">上传Word文档</el-button>
        </el-upload>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitGenerate">确 定</el-button>
          <el-button @click="cancelGenerate">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion, listCircle, listDigest, generateQuestionsAndInsert } from "@/api/question/question";
import { computed, watch, onMounted } from 'vue';
import { parseTime } from "@/utils/ruoyi";
import mammoth from 'mammoth';

const { proxy } = getCurrentInstance();
const { question_type, question_status } = proxy.useDict('question_type', 'question_status');

// 处理题目状态字典，确保启用状态显示为绿色
const processedQuestionStatus = computed(() => {
  return question_status.value.map(item => ({
    ...item,
    elTagType: item.value === '1' ? 'success' : 'danger'
  }));
});

const questionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const circleOptions = ref([]); // 圈子选项列表
const digestOptions = ref([]); // AI生成文章选项列表
const selectedIds = ref([]); // 选中的卡片ID
const expandedCards = ref([]); // 展开的卡片ID

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    circleId: null,
    generatedTextId: null,
    questionTitle: null,
    questionType: null,
  },
  rules: {
    circleId: [
      { required: true, message: "所属圈子不能为空", trigger: "change" }
    ],
    generatedTextId: [
      { required: true, message: "所属文章不能为空", trigger: "change" }
    ],
    questionTitle: [
      { required: true, message: "问题标题不能为空", trigger: "blur" }
    ],
    questionOptions: [
      { required: true, message: "选项不能为空", trigger: "blur" }
    ],
    correctAnswer: [
      { required: true, message: "正确答案不能为空", trigger: "blur" }
    ],
    rewardPoints: [
      { required: true, message: "答对奖励积分不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 操作按钮配置
const actionButtons = computed(() => [
  { type: 'primary', icon: 'Plus', text: '新增', handler: handleAdd, permission: ['question:question:add'], disabled: false },
  { type: 'success', icon: 'Edit', text: '修改', handler: handleUpdate, permission: ['question:question:edit'], disabled: single.value },
  { type: 'danger', icon: 'Delete', text: '删除', handler: handleDelete, permission: ['question:question:remove'], disabled: multiple.value },
  { type: 'warning', icon: 'Download', text: '导出', handler: handleExport, permission: ['question:question:export'], disabled: false },
  { type: 'info', icon: 'Magic', text: 'AI生成题目', handler: handleGenerate, permission: ['question:question:add'], disabled: false }
]);

// AI生成题目相关数据
const generateOpen = ref(false);
const generateForm = ref({
  circleId: undefined,
  generatedTextId: undefined,
  rewardPoints: undefined,
  questionStatus: undefined,
  generatedTitle: '',
  generatedArticle: ''
});
const generateRules = {
  rewardPoints: [
    { required: true, message: "答对奖励积分不能为空", trigger: "blur" }
  ],
  questionStatus: [
    { required: true, message: "题目状态不能为空", trigger: "change" }
  ]
};

/** 查询题目管理列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    // 确保AI生成文章列表已加载
    if (digestOptions.value.length === 0) {
      getDigestList();
    }
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    questionCode: null,
    circleId: null,
    generatedTextId: null,
    questionTitle: null,
    questionType: 1,
    questionOptions: [
      { optionId: 'A', optionContent: '' },
      { optionId: 'B', optionContent: '' }
    ],
    correctAnswer: '',
    answerExplanation: null,
    rewardPoints: null,
    answerCount: null,
    correctCount: null,
    viewCount: null,
    lastAnswerTime: null,
    questionStatus: null,
    createdBy: null,
    createdTime: null,
    updatedBy: null,
    updatedTime: null,
    deletedFlag: null
  };
  proxy.resetForm("questionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  selectedIds.value = [];
  expandedCards.value = [];
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  selectedIds.value = [];
  expandedCards.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

// 卡片选择处理
function handleCardSelection(id, checked) {
  if (checked) {
    if (!selectedIds.value.includes(id)) {
      selectedIds.value.push(id);
    }
  } else {
    selectedIds.value = selectedIds.value.filter(item => item !== id);
  }
  ids.value = selectedIds.value;
  single.value = selectedIds.value.length != 1;
  multiple.value = !selectedIds.value.length;
}

// 切换卡片展开状态
function toggleExpand(id) {
  const index = expandedCards.value.indexOf(id);
  if (index > -1) {
    expandedCards.value.splice(index, 1);
  } else {
    expandedCards.value.push(id);
  }
}

// 解析选项数据
function parseOptions(options) {
  if (!options) return [];
  try {
    const parsedOptions = JSON.parse(options);
    return Array.isArray(parsedOptions) ? parsedOptions : [];
  } catch (e) {
    return [];
  }
}

// 判断是否为正确答案
function isCorrectAnswer(optionId, correctAnswer, questionType) {
  if (!correctAnswer) return false;
  try {
    let answers = correctAnswer;
    if (typeof correctAnswer === 'string') {
      answers = JSON.parse(correctAnswer);
    }
    if (Array.isArray(answers)) {
      return answers.includes(optionId);
    } else {
      return answers === optionId;
    }
  } catch (e) {
    return false;
  }
}

// 格式化正确答案显示
function formatCorrectAnswer(correctAnswer, questionType) {
  if (!correctAnswer) return '';
  try {
    let answers = correctAnswer;
    if (typeof correctAnswer === 'string') {
      answers = JSON.parse(correctAnswer);
    }
    if (Array.isArray(answers)) {
      return answers.join(', ');
    } else {
      return answers;
    }
  } catch (e) {
    return correctAnswer;
  }
}

// 计算正确率
function calculateCorrectRate(item) {
  if (!item.answerCount || item.answerCount === 0) return 0;
  return Math.round((item.correctCount / item.answerCount) * 100);
}

// 获取元数据项
function getMetaItems(item) {
  return [
    { label: '正确答案', value: formatCorrectAnswer(item.correctAnswer, item.questionType), class: 'correct-answer' },
    { label: '奖励积分', value: item.rewardPoints, class: '' },
    { label: '答题次数', value: item.answerCount || 0, class: '' },
    { label: '答对次数', value: item.correctCount || 0, class: '' },
    { label: '正确率', value: `${calculateCorrectRate(item)}%`, class: '' }
  ];
}

// 获取信息项
function getInfoItems(item) {
  const items = [
    { label: '所属圈子', value: getCircleNameById(item.circleId), class: 'circle-name' },
    { label: '所属文章', value: getArticleTitleById(item.generatedTextId), class: '' }
  ];
  if (item.lastAnswerTime) {
    items.push({
      label: '最后答题',
      value: parseTime(item.lastAnswerTime, '{y}-{m}-{d} {h}:{i}'),
      class: ''
    });
  }
  return items;
}

// 获取卡片操作
function getCardActions(item) {
  return [
    { type: 'primary', icon: 'Edit', text: '修改', handler: () => handleUpdate(item), permission: ['question:question:edit'] },
    { type: 'danger', icon: 'Delete', text: '删除', handler: () => handleDelete(item), permission: ['question:question:remove'] }
  ];
}

// 获取表单字段
function getFormFields() {
  return [
    {
      prop: 'circleId',
      label: '所属圈子',
      placeholder: '请选择所属圈子',
      class: 'form-item-half circle-form-item',
      options: circleOptions.value.map(item => ({ id: item.id, label: item.name, value: item.id }))
    },
    {
      prop: 'generatedTextId',
      label: '所属文章',
      placeholder: '请选择所属文章',
      class: 'form-item-half',
      options: digestOptions.value.map(item => ({ id: item.id, label: item.title, value: item.id }))
    }
  ];
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加题目管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getQuestion(_id).then(response => {
    const data = response.data;
    console.log('获取到的题目数据:', data); // 添加日志

    // 类型转换
    data.questionType = parseInt(data.questionType);
    data.questionStatus = parseInt(data.questionStatus);
    data.generatedTextId = parseInt(data.generatedTextId); // 确保generatedTextId是数字类型

    // 处理 questionOptions
    if (typeof data.questionOptions === 'string') {
      try {
        data.questionOptions = JSON.parse(data.questionOptions);
      } catch {
        data.questionOptions = [];
      }
    }

    // 处理 correctAnswer
    let correctAnswer = data.correctAnswer;

    // 递归解析JSON字符串
    function parseAnswer(answer) {
      if (typeof answer === 'string') {
        try {
          const parsed = JSON.parse(answer);
          if (typeof parsed === 'string') {
            return parseAnswer(parsed);
          }
          return parsed;
        } catch {
          return answer;
        }
      }
      return answer;
    }

    correctAnswer = parseAnswer(correctAnswer);

    // 根据题型处理答案格式
    if (data.questionType === 1) {
      // 单选题：需要字符串
      if (Array.isArray(correctAnswer)) {
        correctAnswer = correctAnswer[0] || '';
      }
      correctAnswer = correctAnswer || '';
    } else if (data.questionType === 2) {
      // 多选题：需要数组
      if (!Array.isArray(correctAnswer)) {
        correctAnswer = correctAnswer ? [correctAnswer] : [];
      }
      // 确保答案中的选项在 questionOptions 中存在
      const availableOptions = data.questionOptions.map(opt => opt.optionId);

      // 检查是否需要补充选项
      correctAnswer.forEach(answer => {
        if (!availableOptions.includes(answer)) {
          data.questionOptions.push({
            optionId: answer,
            optionContent: '' // 空内容，用户需要手动填写
          });
        }
      });

    } else if (data.questionType === 3) {
      // 判断题：需要字符串，特殊处理
      if (Array.isArray(correctAnswer)) {
        correctAnswer = correctAnswer[0] || '';
      }
      correctAnswer = correctAnswer || '';

      // 确保判断题有正确的选项
      data.questionOptions = [
        { optionId: 'A', optionContent: '正确' },
        { optionId: 'B', optionContent: '错误' }
      ];
    }

    // 如果选项为空或不足，设置默认选项
    if (!data.questionOptions || data.questionOptions.length === 0) {
      if (data.questionType === 3) {
        data.questionOptions = [
          { optionId: 'A', optionContent: '正确' },
          { optionId: 'B', optionContent: '错误' }
        ];
      } else {
        data.questionOptions = [
          { optionId: 'A', optionContent: '' },
          { optionId: 'B', optionContent: '' }
        ];
      }
    }

    data.correctAnswer = correctAnswer;

    // 确保文章列表已加载
    if (digestOptions.value.length === 0) {
      getDigestList().then(() => {
        form.value = data;
        open.value = true;
        title.value = "修改题目管理";
      });
    } else {
      form.value = data;
      open.value = true;
      title.value = "修改题目管理";
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      // 转换数据格式
      const submitData = { ...form.value };
      // 将选项数组转换为JSON字符串
      submitData.questionOptions = JSON.stringify(form.value.questionOptions);
      // 将答案转换为JSON字符串数组
      if (form.value.questionType === 2) {
        // 多选题，答案本身就是数组
        submitData.correctAnswer = JSON.stringify(form.value.correctAnswer);
      } else {
        // 单选题/判断题，答案是单个值，转为数组再转JSON
        submitData.correctAnswer = JSON.stringify([form.value.correctAnswer]);
      }
      if (form.value.id != null) {
        updateQuestion(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addQuestion(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除题目管理编号为"' + _ids + '"的数据项？').then(function() {
    return delQuestion(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('question/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}

// 添加选项
function addOption() {
  const optionId = String.fromCharCode(65 + form.value.questionOptions.length); // A, B, C...
  form.value.questionOptions.push({
    optionId: optionId,
    optionContent: ''
  });
}

// 删除选项
function removeOption(index) {
  form.value.questionOptions.splice(index, 1);
  // 重新生成选项ID
  form.value.questionOptions.forEach((option, idx) => {
    option.optionId = String.fromCharCode(65 + idx);
  });
}

// 监听题目类型变化
watch(() => form.value.questionType, (newType, oldType) => {
  // 关键修复：只在新增时才重置数据，编辑时不重置
  if (form.value.id != null) {
    return; // 编辑模式，不重置数据
  }

  // 只在新增模式下才重置数据
  if (newType === 3) {
    form.value.questionOptions = [
      { optionId: 'A', optionContent: '正确' },
      { optionId: 'B', optionContent: '错误' }
    ];
    form.value.correctAnswer = '';
  } else {
    form.value.questionOptions = [
      { optionId: 'A', optionContent: '' },
      { optionId: 'B', optionContent: '' }
    ];
    form.value.correctAnswer = newType === 2 ? [] : '';
  }
}, { immediate: false }); // 确保不立即执行

// 格式化选项，只显示选项ID
function formatOptions(options) {
  if (!options) return '';
  try {
    const parsedOptions = JSON.parse(options);
    return parsedOptions.map(opt => opt.optionId).join(', ');
  } catch (e) {
    return options;
  }
}

// 获取圈子列表
function getCircleList() {
  listCircle().then(response => {
    if (response.code === 200 && response.rows) {
      circleOptions.value = response.rows.map(item => ({
        id: item.id,
        name: item.circleName || item.name || `圈子${item.id}`
      }));
    } else {
      circleOptions.value = [];
      proxy.$modal.msgError("获取圈子列表失败");
    }
  }).catch(() => {
    circleOptions.value = [];
    proxy.$modal.msgError("获取圈子列表失败");
  });
}

// 获取AI生成文章列表
function getDigestList() {
  listDigest().then(response => {
    if (response.code === 200 && response.rows) {
      digestOptions.value = response.rows.map(item => ({
        id: item.id,
        title: item.generatedTitle || `AI生成文章${item.id}`
      }));
    } else {
      digestOptions.value = [];
      proxy.$modal.msgError("获取AI生成文章列表失败");
    }
  }).catch(error => {
    digestOptions.value = [];
    proxy.$modal.msgError("获取AI生成文章列表失败");
  });
}

// 添加获取圈子名称的方法
function getCircleNameById(id) {
  if (!id) return '';
  const circle = circleOptions.value.find(item => item.id === id);
  return circle ? (circle.name || `圈子${id}`) : `圈子${id}`;
}

// 添加获取AI生成文章标题的方法
function getArticleTitleById(id) {
  if (!id) return '';
  const digest = digestOptions.value.find(item => item.id === id);
  return digest ? digest.title : `AI生成文章${id}`;
}

// 在组件挂载时获取圈子列表和文章列表
onMounted(() => {
  getCircleList();
  getDigestList();
});

// 打开AI生成题目对话框
function handleGenerate() {
  generateForm.value = {
    circleId: undefined,
    generatedTextId: undefined,
    rewardPoints: undefined,
    questionStatus: undefined,
    generatedTitle: '',
    generatedArticle: ''
  };
  generateOpen.value = true;
}

// 取消AI生成题目
function cancelGenerate() {
  generateOpen.value = false;
  resetGenerate();
}

// 重置AI生成题目表单
function resetGenerate() {
  generateForm.value = {
    circleId: undefined,
    generatedTextId: undefined,
    rewardPoints: undefined,
    questionStatus: undefined,
    generatedTitle: '',
    generatedArticle: ''
  };
  proxy.resetForm("generateRef");
}

// 提交AI生成题目
function submitGenerate() {
  proxy.$refs["generateRef"].validate(valid => {
    if (valid) {
      loading.value = true; // 添加loading状态
      // 确保所有参数都被正确传递
      const submitData = {
        ...generateForm.value,
        rewardPoints: Number(generateForm.value.rewardPoints),
        questionStatus: Number(generateForm.value.questionStatus)
      };
      // 显示生成中的提示
      const loadingInstance = proxy.$loading({
        lock: true,
        text: '正在生成题目，请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      generateQuestionsAndInsert(submitData).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess(response.msg || "生成成功");
          generateOpen.value = false;
          resetGenerate(); // 重置表单
          getList(); // 刷新列表
        } else {
          proxy.$modal.msgError(response.msg || "生成失败");
        }
      }).catch(error => {
        // 如果是超时错误，显示特殊提示
        if (error.message && error.message.includes('timeout')) {
          proxy.$modal.msgSuccess("题目正在后台生成中，请稍后刷新页面查看");
        } else {
          proxy.$modal.msgError("生成失败：" + error.message);
        }
      }).finally(() => {
        loading.value = false; // 结束loading状态
        loadingInstance.close(); // 关闭loading提示
      });
    }
  });
}

function handleWordUpload(file) {
  const reader = new FileReader();
  reader.onload = function(event) {
    const arrayBuffer = event.target.result;
    mammoth.extractRawText({ arrayBuffer }).then(result => {
      generateForm.value.generatedArticle = result.value;
      proxy.$modal.msgSuccess('Word文档内容已自动填充到文章内容');
    }).catch(() => {
      proxy.$modal.msgError('Word文档解析失败，请确认文件格式');
    });
  };
  reader.readAsArrayBuffer(file);
  return false; // 阻止自动上传
}

getList();
</script>

<style scoped>
.question-cards-container {
  margin: 20px 0;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.question-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.question-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  overflow: hidden;
}

.question-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.question-card.selected {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  margin-left: 12px;
}

.question-number {
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.question-type {
  margin-left: auto;
}

.circle-indicator {
  color: #409eff;
  font-weight: 600;
  font-size: 13px;
  margin-left: 12px;
  padding: 2px 8px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 4px;
}

.card-status {
  margin-left: 12px;
}

.card-content {
  padding: 20px;
}

.question-title-section {
  margin-bottom: 16px;
  position: relative;
}

.question-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.5;
  margin: 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  transition: all 0.3s ease;
}

.question-title.expanded {
  -webkit-line-clamp: unset;
  display: block;
}

.expand-btn {
  position: absolute;
  right: 0;
  top: 0;
  color: #409eff;
  font-size: 12px;
  padding: 0;
  height: auto;
}

.question-options {
  margin-bottom: 16px;
}

.options-title {
  font-weight: 600;
  color: #606266;
  margin-bottom: 8px;
  font-size: 14px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.option-item {
  display: flex;
  align-items: flex-start;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.option-item.correct {
  background: #f0f9ff;
  border-left-color: #67c23a;
}

.option-id {
  font-weight: bold;
  color: #409eff;
  margin-right: 8px;
  min-width: 20px;
}

.option-content {
  color: #606266;
  line-height: 1.4;
  flex: 1;
}

.question-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-label {
  font-size: 12px;
  color: #909399;
  font-weight: 500;
}

.meta-value {
  font-size: 14px;
  color: #303133;
  font-weight: 600;
}

.correct-answer {
  color: #67c23a;
}

.question-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background: #fafafa;
  border-radius: 6px;
  border-left: 3px solid #e4e7ed;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  font-size: 13px;
  color: #909399;
  min-width: 70px;
}

.info-value {
  font-size: 13px;
  color: #606266;
  flex: 1;
  word-break: break-all;
}

/* 圈子名称样式 */
.circle-name {
  color: #409eff !important;
  font-weight: 600 !important;
  font-size: 14px !important;
}

/* 表单中圈子选择样式 */
.circle-form-item :deep(.el-form-item__label) {
  color: #409eff !important;
  font-weight: 600 !important;
}

/* 题目状态标签样式 - 启用状态显示为绿色 */
:deep(.el-tag--success) {
  background-color: #f0f9ff !important;
  border-color: #67c23a !important;
  color: #67c23a !important;
}

:deep(.el-tag--danger) {
  background-color: #fef0f0 !important;
  border-color: #f56c6c !important;
  color: #f56c6c !important;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-top: 1px solid #e4e7ed;
}

/* 表单对话框样式 */
.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 18px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.form-item-half {
  flex: 1;
  margin-bottom: 0 !important;
}

.options-container {
  width: 100%;
}

.options-container .option-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  gap: 8px;
}

.options-container .option-item:last-child {
  margin-bottom: 0;
}

/* 对话框和表单样式 */
:deep(.el-dialog__body) {
  max-height: 70vh;
  overflow-y: auto;
  padding: 20px 30px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .question-cards { grid-template-columns: 1fr; }
  .question-meta { grid-template-columns: repeat(2, 1fr); }
  .card-header { flex-direction: column; align-items: flex-start; gap: 8px; }
  .card-title { margin-left: 0; }
  .card-status { margin-left: 0; }
  .form-row { flex-direction: column; gap: 0; }
  .form-item-half { margin-bottom: 18px !important; }
  .form-item-half:last-child { margin-bottom: 0 !important; }
  :deep(.el-dialog) { width: 95% !important; margin: 5vh auto !important; }
  :deep(.el-dialog__body) { padding: 15px 20px; }
}

@media (max-width: 480px) {
  .question-meta { grid-template-columns: 1fr; }
  .card-content { padding: 16px; }
  .card-actions { padding: 12px 16px; }
  :deep(.el-dialog) { width: 98% !important; margin: 2vh auto !important; }
  :deep(.el-dialog__body) { padding: 10px 15px; }
  :deep(.el-form-item__label) { font-size: 14px; }
}

/* AI生成题目对话框美化 */
.ai-generate-form {
  margin-top: 10px;
}
.ai-generate-form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 18px;
}
.form-item-half {
  flex: 1;
  min-width: 0;
}
.form-item-quarter {
  flex: 1.1;
  min-width: 0;
}
.form-item-full {
  flex: 1 1 100%;
  width: 100%;
}
@media (max-width: 768px) {
  .ai-generate-form-row { flex-direction: column; gap: 0; }
  .form-item-half, .form-item-quarter, .form-item-full { margin-bottom: 18px !important; width: 100%; }
  .form-item-half:last-child, .form-item-quarter:last-child, .form-item-full:last-child { margin-bottom: 0 !important; }
}

.ai-article-textarea {
  width: 100%;
  min-height: 220px;
  font-size: 15px;
}

.word-upload-btn {
  margin-bottom: 10px;
}
</style>
